package org.andy.dblock.manager.impl;

import java.sql.Connection;
import java.sql.SQLException;

import org.andy.dblock.entity.MethodLock;
import org.andy.dblock.manager.DataSourceManager;
import org.andy.dblock.manager.DbLockManager;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 锁实现<br>
 *
 * @author andy
 * @version V1.0
 * @date 18/2/7 下午2:24
 */
public class DbLockManagerImpl implements DbLockManager {

    private static final Logger LOG = LoggerFactory.getLogger(DbLockManagerImpl.class);

    private static final QueryRunner QUERY_RUNNER = new QueryRunner(DataSourceManager.getDataSource());

    public static String selectSql
        = "select id,method_name as methodName, description, update_time as updateTime  from method_lock where "
        + "method_name = ?";

    public static String insertSql = "insert method_lock(method_name, description) values(?,?)";

    public static String deleteSql = "delete from method_lock where method_name = ?";

    @Override
    public boolean lock(String methodName) {
        boolean isLock = false;
        try {
            MethodLock methodLock = QUERY_RUNNER.query(selectSql, new BeanHandler<>(MethodLock.class),
                new Object[] {methodName});
            if (methodLock == null) {
                int result = QUERY_RUNNER.update(insertSql, new Object[] {methodName, "desc"});
                if (result == 1) {
                    LOG.info("获取锁 thread id = {}", Thread.currentThread().getId());
                    isLock = true;
                }
                return isLock;
            }

        } catch (SQLException e) {
            LOG.error("加锁失败，methodName = {}", methodName);
        }
        return isLock;
    }

    @Override
    public void unLock(String methodName) {
        try {
            MethodLock methodLock = QUERY_RUNNER.query(selectSql, new BeanHandler<>(MethodLock.class),
                new Object[] {methodName});
            if (methodLock != null){
                QUERY_RUNNER.update(deleteSql, new Object[]{methodName});
            }
        } catch (SQLException e) {
            LOG.error("释放锁异常，methodName = {}", methodName);
        }
    }

}
